package com.tuyulong.mybatis.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import cn.hutool.crypto.digest.HMac;
import org.apache.tomcat.util.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;

/**
 * @program: Interceptor
 * @description:
 * @author: tuyulong
 * @create: 2023-06-05 14:23
 **/
public class RSAUtils {
    private static String publicKey;
    private static String privateKey;

    private static Sign sign;

    static {
        sign = SecureUtil.sign(SignAlgorithm.MD5withRSA);
        KeyPair rsa = SecureUtil.generateKeyPair("RSA");
        privateKey = new String(Base64.encodeBase64(rsa.getPrivate().getEncoded()));
        publicKey = new String(Base64.encodeBase64(rsa.getPublic().getEncoded()));
    }


    public static String encrypt(String data) {

        RSA rsa = SecureUtil.rsa(privateKey, publicKey);
        String s = rsa.encryptHex(data, KeyType.PrivateKey);
        return s;
    }

    public static String decrypt(String data){
        RSA rsa = SecureUtil.rsa(privateKey, publicKey);
        String s = rsa.decryptStr(data, KeyType.PublicKey);
        return s;
    }

    public static String sign(String data) {
        String s = sign.signHex(data);
        return s;
    }

    public static boolean verifySign(String data, String signStr){
        boolean verify = sign.verify(data.getBytes(StandardCharsets.UTF_8), HexUtil.decodeHex(signStr));
        return verify;
    }



}
